package com.java1412.controller.api;

import com.java1412.dto.UserDto;
import com.java1412.service.UserService;
import com.java1412.utils.ConstantUtil;
import com.java1412.utils.ResponseUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author java1412
 * @since 2023-08-07 09:31:29
 */
@RestController
@RequestMapping(value = "/api/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    // 登录
    @PostMapping(value = "/login")
    public Object login(
            @RequestParam(value = "username", required = true) String username,
            @RequestParam(value = "password", required = true) String password,
            HttpSession session
    ) {
        ResponseUtil r = userService.findByUsername(username, password);
        // 登录成功
        if (r.getCode().intValue() == 200) {
            Object user = r.getData();
            session.setAttribute(ConstantUtil.LOGIN_USER_KEY, user);
        }
        return r;
    }

    // 获取用户信息
    @GetMapping(value = "/getCurrentUser")
    public Object getCurrentUser(HttpSession session) {
        ResponseUtil r = null;
        Object user = session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        System.out.println(user);
        if (user == null) {
            r = ResponseUtil.fail("用户未登录");
        } else {
            r = ResponseUtil.ok("用户已登录", user);
        }
        return r;
    }

    @PostMapping(value = "/register")
    public Object register(UserDto userDto) {
        ResponseUtil r = null;
        // 根据uuid获取redis中手机号和验证码
        String phoneAndCode = stringRedisTemplate.opsForValue().get(userDto.getUuid());
        if (null == phoneAndCode) {
            // 已经超时
            r = ResponseUtil.fail("验证码超时，注册失败!");
        } else {
            String phone = phoneAndCode.split("-")[0];
            String code = phoneAndCode.split("-")[1];
            if (phone.equals(userDto.getPhone()) && code.equals(userDto.getCode())) {
                // 校验通过的，执行注册
                r = userService.add(userDto);
                // 删除redis中的手机号和验证码
                stringRedisTemplate.delete(userDto.getUuid());
            } else {
                r = ResponseUtil.fail("手机号和验证码不匹配!");
            }
        }
        return r;
    }
}
